package com.amorcloud.pig.activity;

import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.IBinder;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amorcloud.pig.MyApp;
import com.amorcloud.pig.R;
import com.amorcloud.pig.bean.PigInfoBean;
import com.amorcloud.pig.receiver.BleReceiver;
import com.amorcloud.pig.utils.DateUtil;
import com.amorcloud.pig.utils.GPSUtils;
import com.amorcloud.pig.utils.PigDaoUtils;
import com.amorcloud.pig.utils.RFIDUtil;
import com.amorcloud.pig.utils.ScanQRCodeUtil;
import com.amorcloud.pig.utils.SharedPreferencesUtils;
import com.amorcloud.pig.utils.ToastUtil;
import com.amorcloud.pig.widget.CommonPopupWindow;
import com.amorcloud.pig.widget.CustomToolbar;
import com.rscja.deviceapi.RFIDWithUHF;
import com.rscja.deviceapi.exception.ConfigurationException;
import com.smartahc.android.smartble.SmartAHC;
import com.smartahc.android.smartble.constant.Constant;
import com.smartahc.android.smartble.service.BleService;
import com.smartahc.android.smartble.service.LocalBinder;

import java.util.UUID;

import HJ.EpcDecode.Decode;

public class PigInfoActivity extends BaseActivity implements View.OnClickListener, GPSUtils.OnLocationResultListener ,
        BleReceiver.SearchConnectionListner {

    TextView tvLonTitle, tvLatTitle, tvTime, tvSex, tvLon, tvLat, tvFarmId;
    Button qrCode, rfid, btnQian, save;
    EditText etvFid, etvSowId, etvHogId, etvBirthWeight, etvWeaningWeight;
    Spinner spLeftNipple, spRightNipple;
    //扫描二维码工具类
    ScanQRCodeUtil scanQRCodeUtil;
    //RFID读取工具类
    RFIDUtil rfidUtil;
    String farmId;
    BleService bleService;
    BleReceiver receiver;

    @Override
    protected void init() {
        initView();
        initData();
    }

    private void initView() {
        setContentView(R.layout.activity_piginfo);
        initCustomToolbar(this);
        CustomToolbar toolbar = findViewById(R.id.custom_toolbar);
        toolbar.showPigList();
        //经纬度title
        tvLonTitle = findViewById(R.id.tv_lon_title);
        tvLonTitle.setText(Html.fromHtml("<font color='#FF0000'>*</font> 经度："));
        tvLatTitle = findViewById(R.id.tv_lat_title);
        tvLatTitle.setText(Html.fromHtml("<font color='#FF0000'>*</font> 纬度："));
        //经纬度
        tvLon = findViewById(R.id.tv_lon);
        tvLat = findViewById(R.id.tv_lat);
        //时间
        tvTime = findViewById(R.id.tv_time);
        tvTime.setText(DateUtil.getYMDHMSStrDate(System.currentTimeMillis()));
        //仔猪性别
        tvSex = findViewById(R.id.tv_sex);
        tvSex.setOnClickListener(this);
        //二维码按钮
        qrCode = findViewById(R.id.btn_qrcode);
        qrCode.setOnClickListener(this);
        //rfid按钮
        rfid = findViewById(R.id.btn_rfid);
        rfid.setOnClickListener(this);
        //仔猪电子耳标号
        etvFid = findViewById(R.id.etv_fid);
        //母猪场ID
        tvFarmId = findViewById(R.id.tv_farm_id);
        //母猪耳号
        etvSowId = findViewById(R.id.etv_sow_id);
        //仔猪耳号
        etvHogId = findViewById(R.id.etv_hog_id);
        //左乳头数
        spLeftNipple = findViewById(R.id.sp_left_nipple);
        //右乳头数
        spRightNipple = findViewById(R.id.sp_right_nipple);
        //分娩重量
        etvBirthWeight = findViewById(R.id.etv_birth_weight);
        //断奶重量
        etvWeaningWeight = findViewById(R.id.etv_weaning_weight);
        save = findViewById(R.id.btn_save_piginfo);
        save.setOnClickListener(this);

        btnQian = findViewById(R.id.btn_qian);
        btnQian.setOnClickListener(this);
    }

    private void initData() {
        receiver = new BleReceiver();
        farmId = (String) SharedPreferencesUtils.getParam("farmId", "");

        scanQRCodeUtil = new ScanQRCodeUtil(etvFid, PigInfoActivity.this);
        rfidUtil = new RFIDUtil(etvFid, PigInfoActivity.this);
        SmartAHC.init(PigInfoActivity.this, MyApp.UHF_APP_KEY);

        initErBiaoQian();
        if (!TextUtils.isEmpty(MyApp.lat) && !TextUtils.isEmpty(MyApp.lon)) {
            tvLon.setText(MyApp.lon);
            tvLat.setText(MyApp.lat);
        } else {
            GPSUtils.getInstance(this).setLocationListener(this);
            GPSUtils.getInstance(this).getLngAndLat();
        }
        if (TextUtils.isEmpty(farmId)) {
            Toast.makeText(this, "尚未设置母猪场ID", Toast.LENGTH_SHORT).show();
        } else {
            tvFarmId.setText(farmId);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void initErBiaoQian() {
        bindService(new Intent(this, BleService.class), connection, Context.BIND_AUTO_CREATE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BLE_EAR_TAG_PARSE_MSG);
        filter.addAction(Constant.BLE_MESSAGE_DEVICE_CONNECT);
        filter.addAction(Constant.BLE_MESSAGE_DEVICE_DISCONNECT);
        filter.addAction(Constant.BLE_MESSAGE_DEVICE_FOUND);
        registerReceiver(receiver, filter);
        receiver.setListner(this);
    }

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bleService = ((LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bleService = null;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 208:
            case 280: //rfid读取的物理按钮
                rfidUtil.startRead();
                break;
            case 139: //二维码的物理按钮
                scanQRCodeUtil.ScanBarcode();
                break;
            default:
                return super.onKeyDown(keyCode, event);
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sex:
                showSexPopWindow();
                break;
            case R.id.btn_rfid:
                rfidUtil.startRead();
                break;
            case R.id.btn_qrcode:
                scanQRCodeUtil.ScanBarcode();
                break;
            case R.id.btn_save_piginfo:
                savePigInfo();
                break;
            case R.id.btn_qian:
                boolean result = bindService(new Intent(this, BleService.class), connection, Context.BIND_AUTO_CREATE);
                if(bleService != null) {
                    if(bleService.isBleStart()) {
                        bleService.search();
                    } else {
                        Toast.makeText(this, "请打开蓝牙", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            default:
                break;
        }
    }

    private void savePigInfo() {
        String id = UUID.randomUUID().toString();
        String sowFarmId = tvFarmId.getText().toString();
        String sowId = etvSowId.getText().toString();
        String time = tvTime.getText().toString();
        String hogId = etvHogId.getText().toString();
        String sex = tvSex.getText().toString();
        String leftNipple = spLeftNipple.getSelectedItem().toString();
        String rightNipple = spRightNipple.getSelectedItem().toString();
        String birthWeight = etvBirthWeight.getText().toString();
        String weaningWeight = etvWeaningWeight.getText().toString();
        String lon = tvLon.getText().toString();
        String lan = tvLat.getText().toString();
        String fid = etvFid.getText().toString();
        if (TextUtils.isEmpty(sowFarmId) || TextUtils.isEmpty(fid) || TextUtils.isEmpty(sowId) || TextUtils.isEmpty(time) || TextUtils.isEmpty(hogId) ||
                TextUtils.isEmpty(sex) || TextUtils.isEmpty(leftNipple) || TextUtils.isEmpty(rightNipple) /*|| TextUtils.isEmpty(birthWeight) || TextUtils.isEmpty(weaningWeight)*/) {
            Toast.makeText(this, "请完整录入信息", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(lon) || TextUtils.isEmpty(lan)) {
            Toast.makeText(this, "未获取到经纬度信息，禁止提交", Toast.LENGTH_SHORT).show();
            return;
        }
        PigInfoBean bean = new PigInfoBean();
        bean.setId(id);
        bean.setSow(sowId);
        bean.setDateTime(time);
        bean.setHogID(hogId);
        bean.setLTeat(leftNipple);
        bean.setRTeat(rightNipple);
        bean.setSex(sex);
        bean.setPrimaryW(birthWeight);
        bean.setWeaningW(weaningWeight);
        bean.setLon(lon);
        bean.setLat(lan);
        bean.setUHFID(fid);
        bean.setFarmID(sowFarmId);
        long rowid = PigDaoUtils.insertPigInfo(bean);
        Log.d("leihuiming", "rowid = " + rowid);
        clearData();
    }

    private void clearData() {
        tvFarmId.setText(farmId);
        tvTime.setText(DateUtil.getYMDHMSStrDate(System.currentTimeMillis()));
        etvSowId.setText("");
        etvHogId.setText("");
        tvSex.setText("");
        spLeftNipple.setSelection(0);
        spRightNipple.setSelection(0);
        etvBirthWeight.setText("");
        etvWeaningWeight.setText("");
        //tvLon.setText("");
        //tvLat.setText("");
        etvFid.setText("");
        etvFid.requestFocus();
        Toast.makeText(this, "保存成功！", Toast.LENGTH_SHORT).show();
    }

    private void showSexPopWindow() {
        final CommonPopupWindow commonPopupWindow = new CommonPopupWindow(this, R.layout.popwindow_sex, LinearLayout.LayoutParams.MATCH_PARENT, 300) {
            @Override
            protected void initView() {
                View view = getContentView();
                Button male = view.findViewById(R.id.btn_male);
                Button female = view.findViewById(R.id.btn_female);
                male.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tvSex.setText("公");
                        getPopupWindow().dismiss();
                    }
                });
                female.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tvSex.setText("母");
                        getPopupWindow().dismiss();
                    }
                });
            }

            @Override
            protected void initEvent() {

            }

        };
        PopupWindow popupWindow = commonPopupWindow.getPopupWindow();
        // 设置PopupWindow的背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.popwindow_bg)));
        // 设置PopupWindow是否能响应外部点击事件
        popupWindow.setOutsideTouchable(true);
        // 设置PopupWindow是否能响应点击事件
        popupWindow.setTouchable(true);

        commonPopupWindow.showAtLocation(findViewById(R.id.piginfo_contentview), Gravity.BOTTOM, 0, 0);
    }

    @Override
    protected void onDestroy() {
        scanQRCodeUtil.close();
        rfidUtil.closeRFID();
        if(bleService != null) {
            bleService.disConnect();
        }
        SmartAHC.destroy();
        if(receiver != null)
            unregisterReceiver(receiver);
        if(connection != null)
            unbindService(connection);
        super.onDestroy();
    }

    @Override
    public void onLocationResult(Location location) {

    }

    @Override
    public void OnLocationChange(Location location) {
        String lat = dblToLocation(location.getLatitude()) + "N";
        String lon = dblToLocation(location.getLongitude()) + "E";
        tvLat.setText(lat);
        tvLon.setText(lon);
        MyApp.lat = lat;
        MyApp.lon = lon;
        GPSUtils.getInstance(this).removeListener();
    }

    /**
     * @note double 位置 转换成 分 秒
     */
    public static String dblToLocation(double data) {
        String ret_s = "";
        int tmp_i_du = (int) data;
        ret_s = String.valueOf(tmp_i_du) + "°";
        //度小数部分
        double tmp_d_du = data - tmp_i_du;
        int tmp_i_fen = (int) (tmp_d_du * 60);
        ret_s = ret_s.concat(String.valueOf(tmp_i_fen) + "′");
        double tmp_d_fen = tmp_d_du * 60 - tmp_i_fen;
        int tmp_i_miao = (int) (tmp_d_fen * 60);
        ret_s = ret_s.concat(String.valueOf(tmp_i_miao) + "″");
        return ret_s;
    }

    @Override
    public void onDeviceFound(BluetoothDevice device) {
        Log.d("leihuiming", "onDeviceFound name=" + device.getName() + " address= " + device.getAddress());

        if(bleService != null) {
            bleService.stopScanBLE();
            bleService.connect(device.getName(), device.getAddress());
        }
    }

    @Override
    public void onDeviceConnect() {
        Log.d("leihuiming", "onDeviceConnect");
        Toast.makeText(this, "耳标钳已连接", Toast.LENGTH_SHORT).show();
        if(bleService != null) {

        }
    }

    @Override
    public void onDeviceDisConnect(BluetoothDevice device) {
        Log.d("leihuiming", "onDeviceDisConnect");
        if(bleService != null) {

        }
    }

    @Override
    public void onReveiveData(String data) {
        Log.d("leihuiming", "onReveiveData data= " + data);

        if (data.contains("|")) {
            String fid = data.split("|")[0];
            etvFid.setText(fid);
        } else {
            etvFid.setText(data);
        }

    }
}
